import { defineConfig, loadEnv } from 'vite'
import type { ConfigEnv, UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { resolve } from 'path'

// https://vitejs.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
    const root = process.cwd()
    const env = loadEnv(mode, root, '')
    return {
        server: {
            proxy: {
                '/api': {
                    target: 'http://127.0.0.1:6969/',
                    changeOrigin: true,
                    // rewrite: (path) => path.replace(/^\/api/, '/')
                }
            }
        },
        plugins: [
            vue(),
            AutoImport({
                // 自动导入 Vue 相关函数，如：ref, reactive, toRef 等
                imports: ['vue', 'vue-router', 'pinia'],
                dts: "./auto-import.d.ts",
                resolvers: [ElementPlusResolver()],
            }),
            Components({
                resolvers: [ElementPlusResolver({
                    // 在main.ts中全局引入element-plus/theme-chalk/index.css
                    // 避免按需引入导致页面重载
                    importStyle: false
                })],
                directoryAsNamespace: true,
                dts: './components.d.ts'
            })
        ],
        resolve: {
            alias: {
                '@': resolve(__dirname, 'src'),
                '~': resolve(__dirname, 'public'),
                'components': resolve(__dirname, 'src/components')
            },
            extensions: ['.js', '.ts', '.vue', '.json']
        },
        define: {
            // 这里定义全局常量(ES)，main.ts就能读取
            'process.env': process.env,
            // '_APP_TITLE': JSON.stringify('南京中谷芯')
        },
        envDir: './env',
        optimizeDeps: {
            // include: ['element-plus/es']
        }
    }
})
